package br.com.management.mentor.app.listeners.persisters;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Date;

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;

import br.com.management.mentor.app.Config;
import br.com.management.mentor.model.entities.auth.Permission;
import br.com.management.mentor.model.repositories.PermissionsRepository;

import com.google.gson.reflect.TypeToken;

public class PermissionsEntityPersister implements EntityPersister<Permission> {

	@Autowired
	private PermissionsRepository permissionsRepository;

	@Override
	public void persist( EntityManager em , Collection<Permission> entities ) {
		for ( Permission permission : entities ) {
			if ( permissionsRepository.getByName( permission.getName() ) == null ) {
				permission.setCreationDate( new Date() );
				em.persist( permission );
			}
		}
	}

	@Override
	public Config getResourcePath() {
		return Config.PERMISSIONS_SOURCE_FILE;
	}

	@Override
	public Type getEntityType() {
		return new TypeToken<Collection<Permission>>() {}.getType();
	}

}